package com.hs.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hs.entity.pojo.Dialogue;
import com.hs.entity.pojo.Message;
import com.hs.entity.pojo.User;
import com.hs.entity.vo.DialogueVO;
import com.hs.mapper.DialogueMapper;
import com.hs.service.DialogueService;
import com.hs.service.UserService;
import com.hs.utils.BeanCopyUtil;
import com.hs.utils.RedisCache;
import com.hs.utils.ResultResponse;
import com.hs.utils.SecurityUserHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hs
 * @since 2023-08-05
 */
@Service
public class DialogueServiceImpl extends ServiceImpl<DialogueMapper, Dialogue> implements DialogueService {

    @Resource
    private UserService userService;

    @Resource
    private RedisCache redisCache;

    @Override
    public ResultResponse<List<DialogueVO>> getCurrentUserDialogueList() {
        // 先拿到当前用户
        Integer userId = SecurityUserHolder.getUserId();

        List<DialogueVO> dialogueVOS = new ArrayList<>();

        query().eq("the_one_user_id", userId).list().forEach(dialogue -> {
            DialogueVO dialogueVO = BeanCopyUtil.copyBean(dialogue, DialogueVO.class);
            dialogueVO.setCurrentUserId(userId);
            Integer theOtherUserId = dialogue.getTheOtherUserId();
            dialogueVO.setToUserId(theOtherUserId);
            User toUser = userService.getById(theOtherUserId);
            dialogueVO.setToUserNickName(toUser.getNickName());
            dialogueVO.setToUserHead(toUser.getHead());

            Integer unreadCount = getUnreadCount(userId, dialogue.getId());
            dialogueVO.setUnReadCount(unreadCount);

            // 要去redis中该对话的最后一条消息内容
            List<Message> messageList = redisCache.getCacheList("pet:view:dialogue:" + dialogue.getId());

            if (Objects.nonNull(messageList)) {
                // 拿到最后一条消息的内容
                Message message = null;
                try {
                    message = messageList.get(messageList.size() - 1);
                    String messageContent = message.getContent();
                    dialogueVO.setLatestTimeMessageContent(messageContent);
                } catch (ArrayIndexOutOfBoundsException e) {
                    // 出异常则给空字符串
                    dialogueVO.setLatestTimeMessageContent("");
                }

            } else {
                dialogueVO.setLatestTimeMessageContent("哈哈哈");
            }
            dialogueVOS.add(dialogueVO);
        });

        query().eq("the_other_user_id", userId).list().forEach(dialogue -> {
            DialogueVO dialogueVO = BeanCopyUtil.copyBean(dialogue, DialogueVO.class);
            dialogueVO.setCurrentUserId(userId);
            Integer theOneUserId = dialogue.getTheOneUserId();
            dialogueVO.setToUserId(theOneUserId);
            User toUser = userService.getById(theOneUserId);
            dialogueVO.setToUserNickName(toUser.getNickName());
            dialogueVO.setToUserHead(toUser.getHead());
            Integer unreadCount = getUnreadCount(userId, dialogue.getId());
            dialogueVO.setUnReadCount(unreadCount);
            // 要去redis中该对话的最后一条消息内容
            List<Message> messageList = redisCache.getCacheList("pet:view:dialogue:" + dialogue.getId());
            if (Objects.nonNull(messageList)) {
                // 拿到最后一条消息的内容
                Message message = null;
                try {
                    message = messageList.get(messageList.size() - 1);
                    String messageContent = message.getContent();
                    dialogueVO.setLatestTimeMessageContent(messageContent);
                } catch (ArrayIndexOutOfBoundsException e) {
                    // 出异常则给空字符串
                    dialogueVO.setLatestTimeMessageContent("");
                }
            } else {
                dialogueVO.setLatestTimeMessageContent("哈哈哈");
            }
            dialogueVOS.add(dialogueVO);
        });

        List<DialogueVO> dialogueVOList = dialogueVOS.stream().sorted((o1, o2) -> {
            int time1 = (int) o1.getCreateTime().getTime();
            int time2 = (int) o2.getCreateTime().getTime();
            return time2 - time1;
        }).collect(Collectors.toList());
        return ResultResponse.ok(dialogueVOList);
    }

    @Override
    public ResultResponse<Integer> getDialogueIdByUserIds(Integer theOne, Integer theOther) {
        Dialogue dialogue = query().eq("the_one_user_id", theOne)
                .eq("the_other_user_id",theOther)
                .one();
        if (Objects.nonNull(dialogue)){
            return ResultResponse.ok(dialogue.getId());
        }
        dialogue = Optional.ofNullable(query().eq("the_one_user_id", theOther).eq("the_other_user_id",theOne).one()).orElseGet(() -> {
            // 如果数据库没有这个对话则是给它创建一个
            Dialogue dia = new Dialogue();
            dia.setTheOneUserId(theOne);
            dia.setTheOtherUserId(theOther);
            DialogueServiceImpl.this.save(dia);
            return dia;
        });
        return ResultResponse.ok(dialogue.getId());
    }

    private Integer getUnreadCount(Integer userId,Integer dialogueId) {
        List<Message> messages = redisCache.getCacheList("pet:view:dialogue:" + dialogueId);
        List<Message> messageList = messages.stream()
                .filter(message -> message.getMessageReceiver().equals(userId) && !message.getMessageReadFlag())
                .collect(Collectors.toList());
        return messageList.size();
    }
}
